﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;

namespace TimerJobServer.Common
{
    /// <summary>
    /// 配置文件类
    /// </summary>
    public class JSONConfig<T>  where T : new()
    {

        public JSONConfig(string filePath)
        {
            Path = filePath;
        }


        public bool IsFileExists
        {
            get
            {
                return File.Exists(Path);
            }
        }

        /// <summary>
        /// 要保存的文件名称
        /// </summary>
        public string Path { get; set; }

        public T _model;

        public  T Default
        {
            get
            {
                if (_model == null)
                {
                    LoadFromJson();
                }
                return _model;
            }
        }

        public  void LoadFromJson()
        {
            try
            {
                //文件存在才读取
                if (File.Exists(Path))
                {
                    using (FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
                    {
                        StreamReader sr = new StreamReader(fs, Encoding.UTF8);
                        string json = sr.ReadToEnd();
                        _model = JsonConvert.DeserializeObject<T>(json);
                        sr.Close();
                    }
                }

                if (_model == null)
                {
                    _model = new T();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        /// <summary>
        /// 保存信息
        /// </summary>
        public void Save()
        {
            try
            {
                string json = JsonConvert.SerializeObject(_model, Formatting.Indented);
                //如果不存在则创建目录
                FileInfo fi = new FileInfo(Path);
                var dir = fi.Directory;
                if (!dir.Exists)
                {
                    dir.Create();
                }
                System.IO.File.WriteAllText(Path, json, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}
